﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Pawn
{
    public partial class FrmPhieuVay : Form
    {
        DataClassesDataContext db;
        PhieuCam phieu;
        CaiDat cai_dat;
        Khach khach;
        public bool SuaPhieu { get; set; }
        public String SoPhieu
        {
            get
            {
                return tbSoPhieu.Text;
            }
            set
            {
                tbSoPhieu.Text = value;
            }
        }
        public FrmPhieuVay()
        {
            InitializeComponent();
            SuaPhieu = false;
        }
        private static string ChuanHoaSo(int x)
        {
            int n = x.ToString().Length;
            return n < 5 ? new String('0', 5 - n) + x : x.ToString();
        }
        private void FrmChoVay_Load(object sender, EventArgs e)
        {
            db = new DataClassesDataContext();

            if (!SuaPhieu) btnTao_Click(sender, e);
            else
            {
                btnSua_Click(sender, e);
                btnHuy_Click(sender, e);
            }
        }


        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (tbTenKH.Text == "")
            {
                MessageBox.Show("Bạn chưa điền tên khách hàng!");
                return;
            }
            phieu.So = tbSoPhieu.Text;

            khach.HoTen = tbTenKH.Text;
            khach.DiaChi = tbDiaChi.Text;
            khach.CMND = tbCMND.Text;
            khach.LienLac = tbDienThoai.Text;
            if (cbGioiTinh.SelectedIndex == 1) khach.GioiTinh = true;
            else if (cbGioiTinh.SelectedIndex == 2) khach.GioiTinh = false;
            else khach.GioiTinh = null;

            if (tbMaKH.Text=="")
            {
                db.Khaches.InsertOnSubmit(khach);
                db.SubmitChanges();
            }
            phieu.MaKH = khach.Id;
            phieu.NgayLap = dpNgayVay.Value;
            
            phieu.TienVay = tbTienVay.Value;
            phieu.TienVayBangChu = VND.DocSo((Int64)phieu.TienVay);
            phieu.LaiSuat = tbLai.Value;
            phieu.DoCam = tbDoCam.Text;
            phieu.MoTa = tbGhiChu.Text;
            phieu.DaTraTien = false;
           
            foreach (DataGridViewRow r in dgLanDong.Rows)
            {
                if (SuaPhieu)
                {
                    var dls = from dl in phieu.DongLais
                              where dl.Id == Convert.ToInt32(r.Cells["Id"].Value)
                              select dl;
                    bool found = false;
                    foreach (var dl in dls)
                    {
                        found = true;
                        dl.NgayDong = DateTime.ParseExact(r.Cells["NgayDong"].Value.ToString(), "dd/MM/yyyy", null);
                        dl.TienDong = Convert.ToInt64(r.Cells["TienDong"].Value);
                        dl.TienNo = Convert.ToInt64(r.Cells["TienNo"].Value);
                    }
                    if (!found)
                    {
                        DongLai lai = new DongLai()
                        {
                            SoPC = phieu.So,
                            NgayDong = DateTime.ParseExact(r.Cells["NgayDong"].Value.ToString(), "dd/MM/yyyy", null)
                        };
                        phieu.DongLais.Add(lai);
                    }
                }
                else
                {
                    DongLai lai = new DongLai()
                    {
                        SoPC = phieu.So,
                        NgayDong = DateTime.ParseExact(r.Cells["NgayDong"].Value.ToString(), "dd/MM/yyyy", null),
                        TienDong = 0,
                        TienNo= 0
                    };
                    phieu.DongLais.Add(lai);
                }
            }
            
            if (!SuaPhieu) db.PhieuCams.InsertOnSubmit(phieu);
            db.SubmitChanges();
            ResetDG();
            SuaPhieu = true;
            btnHuy_Click(sender, e);
            btnSua.Enabled = true;
            btnIn.Enabled = true;
            
        }
        
        private void btnHuy_Click(object sender, EventArgs e)
        {
            //this.Close();
            btnHuy.Enabled = false;
            btnTao.Enabled = true;
            if (SuaPhieu)
            {
                btnIn.Enabled = true;
            }
            btnLuu.Enabled = false;
            gbPhieu.Enabled = false;
            gbKH.Enabled = false;
            gbVay.Enabled = false;

            if (SuaPhieu && phieu.DaTraTien!=true )
            {
                btnSua.Enabled = true;
                btnDongLai.Enabled = true;
                btnGiaHan.Enabled = true;
                btnXoaHan.Enabled = true;
                btnTraPhieu.Enabled = true;
            }
        }
        private static int TachSo(string s)
        {
            Regex reg = new Regex(@"\d+");
            Match match=reg.Match(s);
            return Convert.ToInt32(match.Groups[0].ToString());
        }
        private static void ResetForm(Control control)
        {
            foreach (Control child in control.Controls)
            {
                if(child.Name.StartsWith("tb")) ((TextBox)child).Text = "";
                if (child.Name.StartsWith("dp")) ((DateTimePicker)child).Value  = DateTime.Now;
                if (child.Name.StartsWith("dgv")) ((DataGridView)child).Rows.Clear();
                if (child.Name.StartsWith("cb")) ((ComboBox)child).SelectedIndex = 0;
                if (child.HasChildren) ResetForm(child);
            }
        }
        private void btnTao_Click(object sender, EventArgs e)
        {
            btnHuy.Enabled = true;
            tbSoPhieu.Enabled = true;
            btnDongLai.Enabled = false;
            btnGiaHan.Enabled = false;
            btnXoaHan.Enabled = false;
            btnTraPhieu.Enabled = false;
            SuaPhieu = false;
            btnTao.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            btnIn.Enabled = false;
            gbKH.Enabled = true;
            gbPhieu.Enabled = true;
            gbVay.Enabled = true;
            dpNgayVay.Value = DateTime.Now;
            ResetForm(this);
            // Load cai dat
            var query = from cd in db.CaiDats
                        select cd;
            foreach (CaiDat c in query) cai_dat = c;

            phieu = new PhieuCam();
            var q = (from p in db.PhieuCams
                     where p.So.StartsWith(cai_dat.TienToPhieu) && p.So.EndsWith(cai_dat.HauToPhieu)
                     orderby p.So descending
                     select p).Skip(0).Take(1);
            tbSoPhieu.Text = cai_dat.TienToPhieu + ChuanHoaSo(0) + cai_dat.HauToPhieu;
            foreach (var tmp in q)
                tbSoPhieu.Text = cai_dat.TienToPhieu + ChuanHoaSo(TachSo(tmp.So)+1)+cai_dat.HauToPhieu;
            
            
            // Lai suat
            tbLai.Value = (Int64)Math.Round((double)cai_dat.LaiSuat, 2);

            // Khach

            khach = new Khach();
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            var q = from p in db.PhieuCams
                    where p.So == tbSoPhieu.Text
                    select p;
            foreach (var p in q)
            {
                phieu = p;
                khach = phieu.Khach;
                tbMaKH.Text = khach.Id.ToString();
                tbTenKH.Text = khach.HoTen;
                tbDiaChi.Text = khach.DiaChi;
                tbDienThoai.Text = khach.LienLac;
                tbCMND.Text = khach.CMND;
                tbTienVay.Value = (Int64)phieu.TienVay;
                tbLai.Value = (Int64)phieu.LaiSuat;
                tbDoCam.Text = phieu.DoCam;
                tbGhiChu.Text = phieu.MoTa;
                cbGioiTinh.SelectedIndex = khach.GioiTinh == null ? 0 : khach.GioiTinh == true ? 1 : 2;
                dpNgayVay.Value = (DateTime)phieu.NgayLap;
                ResetDG();
            }
            btnHuy.Enabled = true;
            btnDongLai.Enabled = false;
            btnGiaHan.Enabled = false;
            btnXoaHan.Enabled = false;
            btnTraPhieu.Enabled = false;
            SuaPhieu = true;
            gbKH.Enabled = true;
            gbPhieu.Enabled = true;
            gbVay.Enabled = true;
            tbSoPhieu.Enabled = false;
            btnTao.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            btnIn.Enabled = false;

        }

        private void ResetDG()
        {
            dgLanDong.Rows.Clear();
            int i = 1;
            var q = from dl in phieu.DongLais
                    orderby dl.NgayDong ascending
                    select dl;
            foreach (var dl in q)
            {
                int r = dgLanDong.Rows.Add();
                dgLanDong.Rows[r].Cells["Lan"].Value = i++;
                dgLanDong.Rows[r].Cells["Id"].Value = dl.Id;
                dgLanDong.Rows[r].Cells["NgayDong"].Value = ((DateTime)dl.NgayDong).ToString("dd/MM/yyyy");
                dgLanDong.Rows[r].Cells["TienDong"].Value = dl.TienDong;
                dgLanDong.Rows[r].Cells["TienNo"].Value = dl.TienNo;
            }
        }

        private void tbMaKH_TextChanged(object sender, EventArgs e)
        {
            if (tbMaKH.Text != "")
            {
                var q = from p in db.Khaches
                        where p.Id == Convert.ToInt32(tbMaKH.Text)
                        select p;
                foreach (var p in q)
                    khach = p;
            }
        }

        private void btnTimKH_Click(object sender, EventArgs e)
        {
            FrmKhach frm = new FrmKhach() { Mode = true };
            if (frm.ShowDialog() == DialogResult.OK)
            {
                tbMaKH.Text = frm.MaKH;
                var q = from k in db.Khaches
                        where k.Id == Convert.ToInt32(tbMaKH.Text)
                        select k;
                foreach (var k in q)
                {
                    tbTenKH.Text = k.HoTen;
                    tbDiaChi.Text = k.DiaChi;
                    tbDienThoai.Text = k.LienLac;
                    tbCMND.Text = k.CMND;
                    cbGioiTinh.SelectedIndex = k.GioiTinh == null ? 0 : k.GioiTinh == true ? 1 : 2;
                    khach = k;
                    break;
                }
            }
            
        }

        private void dpNgayVay_ValueChanged(object sender, EventArgs e)
        {
            if (SuaPhieu) return;
            dgLanDong.Rows.Clear();
            for (int i = 0; i < 3; i++)
            {
                int r = dgLanDong.Rows.Add();
                dgLanDong.Rows[r].Cells["Lan"].Value = i + 1;
                dgLanDong.Rows[r].Cells["NgayDong"].Value = dpNgayVay.Value.AddDays((i + 1) * 10).ToString("dd/MM/yyyy");
            }
        }

        private void btnDongLai_Click(object sender, EventArgs e)
        {
            if (dgLanDong.SelectedRows.Count < 1) return;
            if (Convert.ToInt64(dgLanDong.SelectedRows[0].Cells["TienDong"].Value) != 0)
            {
                MessageBox.Show("Ngày bạn chọn đã được đóng lãi rồi!");
                return;
            }
            var q = from dl in phieu.DongLais
                    where dl.Id == Convert.ToInt32(dgLanDong.SelectedRows[0].Cells["Id"].Value)
                    select dl;
            foreach (var dl in q)
            {
                FrmDongLai frm = new FrmDongLai();
                frm.DL = dl;

                if (frm.ShowDialog() == DialogResult.OK)
                {
                    
                    dl.TienDong = frm.TienDong;
                    dl.TienNo = frm.TienNo;
                    dl.NgayDong = frm.NgayDong;
                    var q1 = from r in phieu.DongLais
                            where r.NgayDong < dl.NgayDong && r.TienDong == 0
                            select r;
                    db.DongLais.DeleteAllOnSubmit(q1);
                    
                    var q2 = from r in phieu.DongLais
                             where r.NgayDong > dl.NgayDong
                             select r;
                    if (q2.Count() < 1) phieu.DongLais.Add(new DongLai() { NgayDong = frm.GiaHan, TienDong = 0, TienNo = 0 });
                    db.SubmitChanges();
                }
                ResetDG();
                break;
            }
        }

        private void btnGiaHan_Click(object sender, EventArgs e)
        {
            var q = (from dl in phieu.DongLais
                     orderby dl.NgayDong descending
                     select dl).Skip(0).Take(1);
            foreach (var dl in q)
            {
                FrmGiaHan frm = new FrmGiaHan() { HanCu = (DateTime)dl.NgayDong };
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    phieu.DongLais.Add(new DongLai() { NgayDong = frm.HanMoi, TienDong = 0, TienNo = 0 });
                    db.SubmitChanges();
                    ResetDG();
                }
            }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            if (btnHuy.Enabled == true)
            {
                if (MessageBox.Show("Dữ liệu chưa được lưu! Bạn có chắc chắn muốn đóng cửa sổ này?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    this.Close();
                }
                return;
            }
            this.Close();
        }

        private void btnXoaHan_Click(object sender, EventArgs e)
        {
            if (dgLanDong.SelectedRows.Count < 1) return;
            DataGridViewRow r= dgLanDong.SelectedRows[0];
            if (Convert.ToInt64(r.Cells["TienDong"].Value) != 0)
            {
                MessageBox.Show("Bạn không thể xóa ngày đã đóng lãi!");
                return;
            }
            if(phieu.DongLais.Count==1)
            {
                MessageBox.Show("Bạn không thể xóa hạn đóng lãi duy nhất!");
                return;
            }
            var q = from dl in phieu.DongLais
                    where dl.Id == Convert.ToInt32(r.Cells["Id"].Value)
                    select dl;
            foreach (var dl in q)
            {
                phieu.DongLais.Remove(dl);
                db.SubmitChanges();
                ResetDG();
                break;
            }
        }

        private void btnXoaKH_Click(object sender, EventArgs e)
        {
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            FrmPVIn frm = new FrmPVIn();
            frm.SoPhieu = tbSoPhieu.Text;
            frm.ShowDialog();
        }

        private void btnTraPhieu_Click(object sender, EventArgs e)
        {
            PhieuCam _p = phieu;
            bool chuadong = true;
            Int64 tienno = 0;
            DateTime ngaydong = ((DateTime)_p.NgayLap).Date;
            DateTime hantra = ngaydong;
            var dl = from d in db.DongLais
                     where d.SoPC == _p.So
                     orderby d.NgayDong descending
                     select d;
            foreach (var d in dl)
            {
                if (hantra == ngaydong) hantra = ((DateTime)d.NgayDong).Date;

                if (d.TienDong != null && d.TienDong != 0)
                {
                    chuadong = false;
                    tienno = (Int64)d.TienNo;
                    ngaydong = ((DateTime)d.NgayDong).Date.AddDays(1);
                    break;
                }
            }
            int songayno = (DateTime.Now.Date.AddDays(1) - ngaydong.Date).Days;
            if (songayno > 0)
            {
                if (chuadong) tienno = (Int64)_p.TienVay * (Int64)_p.LaiSuat * songayno / 1000000;
                else tienno += (Int64)_p.TienVay * (Int64)_p.LaiSuat * songayno / 1000000;
            }
            if (tienno > 0)
            {
                if (MessageBox.Show("Phiếu này vẫn nợ "+tienno.ToString("#,#")+"Đ tiền lãi. Bạn có chắc muốn trả phiếu", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                    return;
            }
            if (MessageBox.Show("Trả phiếu số " + phieu.So + "?", "Xác Nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                phieu.NgayTra = DateTime.Now.Date;
                phieu.DaTraTien = true;
                db.SubmitChanges();
                MessageBox.Show("Đã trả phiếu!", "Thông Tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnHuy_Click(sender, e);
            }
        }
    }
}
